package com.cuit.mimall.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cuit.mimall.common.R;
import com.cuit.mimall.entity.LoginUser;
import com.cuit.mimall.entity.User;
import com.cuit.mimall.mapper.UserMapper;
import com.cuit.mimall.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.parameters.P;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author star
 * @since 2023-07-01
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    /**
     * 添加注册用户
     *
     * @param user 用户信息
     * @return 执行结果
     */
    @Override
    public boolean save(User user) {
        //密码加密器
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        //对密码进行加密
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        return super.save(user);
    }

    /**
     * 获取当前登录用户
     */
    @Override
    public LoginUser getCurrentUser() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        return (LoginUser) authentication.getPrincipal();
    }

    @Override
    public R<?> getUsersByStatus(Integer status, Integer pageNum, Integer pageSize) {
        Page<User> page = new Page<>(pageNum, pageSize);
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", status);
        return R.ok(this.page(page, queryWrapper));
    }

    @Override
    public R<?> getUsers(Integer pageNum, Integer pageSize) {
        Page<User> page = new Page<>(pageNum, pageSize);
        return R.ok("用户获取成功", this.page(page));
    }

    @Override
    public R<?> info() {
        LoginUser loginUser = this.getCurrentUser();
        return R.ok("用户信息获取成功", loginUser);
    }
    @Autowired
    private  UserMapper userMapper;
    @Autowired
    private PasswordEncoder passwordEncoder;

    //前台用户进行密码修改
    public boolean updatePasswordByUserId(Long userId, String oldPassword,String newPassword, String confirmPassword) {
        // 查询用户信息
        User user = userMapper.selectById(userId);
        // 判断用户是否存在
        if (user == null) {
            return false;
        }

        // 判断两次密码是否相同
        if (!newPassword.equals(confirmPassword)) {
            throw new RuntimeException("两次输入密码不一致");
        }

        System.out.println(oldPassword);
        System.out.println(user.getPassword());

        //密码匹配
        if(!passwordEncoder.matches(oldPassword,user.getPassword())){
            throw new RuntimeException("旧密码不正确");
        }
        user.setPassword(passwordEncoder.encode(newPassword));
        int rows = userMapper.updateById(user);

        return rows > 0;
    }


    public boolean updateUserInformation(Long userId, String nickName, String email, String phoneNumber){
        User user = userMapper.selectById(userId);
        if(user==null){
            throw new RuntimeException("User not found");
        }
        user.setNickName(nickName);
        user.setEmail(email);
        user.setPhoneNumber(phoneNumber);
        int rows = userMapper.updateById(user);
        return rows > 0;
    }

    @Override
    public R<?> addUser(User user){
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        int insert = userMapper.insert(user);
        if (insert > 0) {
            return R.ok("添加用户成功", user);
        }else {
            return R.fail("添加用户失败");
        }
    }

    @Override
    public R<?> updateUser(User user) {
        User preUser = userMapper.selectById(user.getUserId());
        if (preUser == null) {
            return R.fail("未找到这个用户");
        }
        int i = userMapper.updateById(user);
        if (i > 0) {
            return R.ok("修改用户成功");
        }else {
            return R.fail("修改用户失败");
        }
    }

}
